package cn.edu.gzhmt.category.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.edu.gzhmt.category.dao.ICategoryDao;
import cn.edu.gzhmt.category.domain.Category;
import cn.edu.gzhmt.utils.jdbc.TxQueryRunner;

/**
 * 分类 dao层实现类
 * @author azhuo
 *
 */
public class CategoryDaoImpl implements ICategoryDao {

	private QueryRunner queryRunner = new TxQueryRunner();

	/**
	 * 查询所有分类
	 */
	public List<Category> findAll() {
		try {
			String sql = "SELECT * FROM t_category WHERE del='0'";

			return queryRunner.query(sql, new BeanListHandler<Category>(
					Category.class));

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Category findById(String cid) {
		try {
			String sql = "SELECT * FROM t_category WHERE cid=? and del='0'";

			return queryRunner.query(sql, new BeanHandler<Category>(
					Category.class), cid);

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 通过id修改分类
	 * cname是必填字段
	 */
	public void updateCategory(Category category) {
		try {
			StringBuffer sqlBuf = new StringBuffer();
			List<Object> params = new ArrayList<Object>();

			sqlBuf.append("UPDATE `t_category` SET cname=?");
			params.add(category.getCname());

			if (category.getCdesc() != null
					&& category.getCdesc().trim().length() > 0) {
				sqlBuf.append(",cdesc=?");
				params.add(category.getCdesc());
			}
			sqlBuf.append(" WHERE cid=? and del='0'");
			params.add(category.getCid());

			queryRunner.update(sqlBuf.toString(), params.toArray());
			
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}

	/**
	 * 按名称查找分类
	 */
	public Category findByCname(String cname) {
		try {
			String sql = "SELECT * FROM t_category WHERE cname=?";

			return queryRunner.query(sql, new BeanHandler<Category>(
					Category.class), cname);

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 添加分类
	 * del字段默认为0，未删除
	 */
	public void addCategory(Category category) {
		try {
			String sql = "INSERT INTO `t_category`(`cid`,`cname`,`cdesc`) VALUES (?,?,?)";
			Object[] params = {category.getCid(), category.getCname(), category.getCdesc()};
			
			queryRunner.update(sql, params);

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 删除分类：假删除
	 * 添加了一个字段“del”,1：表示已经删除
	 */
	public void removeCategoryByCid(String cid) {
		try {
			String sql = "UPDATE `t_category` SET `del`=1 WHERE cid=?";
			
			queryRunner.update(sql, cid);

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	/**
	 * 通过名称删除分类
	 */
	public void removeCategoryByCname(String cname) {
		try {
			String sql = "UPDATE `t_category` SET `del`=1 WHERE cname=?";
			
			queryRunner.update(sql, cname);

		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

}
